package com.consumer.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * Description:
 *
 * @Author: future
 * @Date:2022/8/13:10:03
 */
@RestController
public class DemoController {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${service-url.nacos-user-service:98}")
    private String serviceUrl;

    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping(value = "/consumer/nacos")
    public Integer getDiscovery() {
        return restTemplate.getForObject(serviceUrl + "/getPort", Integer.class);
    }

    @GetMapping("/hello")
    public String hello() {
        List<ServiceInstance> instances = discoveryClient.getInstances("service-provider");
        if (instances.size() == 0) {
            return "No instances available.";
        }
        ServiceInstance instance = instances.get(0);
        String url = instance.getUri() + "/hello";
        RestTemplate restTemplate = new RestTemplate();
        return restTemplate.getForObject(url, String.class);
    }

}
